<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">团购活动</h1>
    
    <div class="mb-6">
      <div class="flex items-center space-x-4 mb-4">
        <button 
          v-for="(tab, index) in tabs" 
          :key="index"
          @click="activeTab = tab.value"
          :class="[
            'px-4 py-2 rounded-md',
            activeTab === tab.value 
              ? 'bg-primary text-white' 
              : 'bg-gray-100 hover:bg-gray-200'
          ]"
        >
          {{ tab.label }}
        </button>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center py-8">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="groupBuys.length === 0" class="text-center py-8">
      <p class="text-gray-500">暂无团购活动</p>
    </div>

    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div 
        v-for="groupBuy in groupBuys" 
        :key="groupBuy.id" 
        class="bg-white rounded-lg shadow-md overflow-hidden"
      >
        <img 
          :src="formatImageUrl(groupBuy.productImage)" 
          :alt="groupBuy.productName"
          class="w-full h-48 object-cover"
          @error="handleImageError"
        />
        <div class="p-4">
          <h2 class="text-xl font-semibold mb-2">{{ groupBuy.productName }}</h2>
          <div class="flex items-center mb-2">
            <span class="text-gray-500 line-through mr-2">¥{{ groupBuy.originalPrice }}</span>
            <span class="text-red-500 font-bold text-xl">¥{{ groupBuy.groupPrice }}</span>
          </div>
          <div class="flex justify-between items-center mb-3">
            <span class="text-sm text-gray-600">
              已参团: {{ groupBuy.joinCount }}/{{ groupBuy.minCount }}人
            </span>
            <span 
              :class="[
                'text-sm px-2 py-1 rounded',
                getStatusClass(groupBuy.status)
              ]"
            >
              {{ getStatusText(groupBuy.status) }}
            </span>
          </div>
          <div class="mb-3">
            <div class="w-full bg-gray-200 rounded-full h-2.5">
              <div 
                class="bg-primary h-2.5 rounded-full" 
                :style="{width: `${Math.min(100, (groupBuy.joinCount / groupBuy.minCount) * 100)}%`}"
              ></div>
            </div>
          </div>
          <div v-if="groupBuy.status === 1" class="text-sm text-gray-600 mb-3">
            <span>距离结束: {{ formatTimeRemaining(groupBuy.endTime) }}</span>
          </div>
          <div v-if="groupBuy.status === 0" class="text-sm text-gray-600 mb-3">
            <span>距离开始: {{ formatTimeRemaining(groupBuy.startTime) }}</span>
          </div>
          <button 
            @click="goToDetail(groupBuy.id)"
            class="w-full py-2 rounded-md hover:opacity-90 transition"
            :class="{
              'bg-blue-500 text-white': groupBuy.status === 0,
              'bg-green-500 text-white': groupBuy.status === 1,
              'bg-gray-500 text-white cursor-not-allowed': groupBuy.status === 2 || groupBuy.status === 3
            }"
          >
            {{ getButtonText(groupBuy.status) }}
          </button>
        </div>
      </div>
    </div>

    <div class="flex justify-center mt-6" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[9, 12, 24, 36]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { onMounted, ref, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'GroupBuyView',
  setup() {
    const router = useRouter()
    const groupBuys = ref([])
    const loading = ref(true)
    const activeTab = ref('ongoing')
    const currentPage = ref(1)
    const pageSize = ref(9)
    const total = ref(0)
    
    const tabs = [
      { label: '进行中', value: 'ongoing' },
      { label: '即将开始', value: 'upcoming' },
      { label: '已结束', value: 'ended' }
    ]

    const fetchGroupBuys = async () => {
      loading.value = true
      try {
        let endpoint = '/api/group-buys'
        let params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        if (activeTab.value === 'ongoing') {
          params.status = 1
        } else if (activeTab.value === 'upcoming') {
          params.status = 0
        } else if (activeTab.value === 'ended') {
          params.status = 2
        }
        
        const response = await axios.get(endpoint, { params })
        if (response.data.code === 200) {
          groupBuys.value = response.data.data.list || []
          total.value = response.data.data.total
          console.log('获取到的团购活动:', response.data.data)
        } else {
          console.error('获取团购活动失败:', response.data.message)
          ElMessage.error(response.data.message || '获取团购活动失败')
        }
      } catch (error) {
        console.error('获取团购活动出错:', error)
        ElMessage.error('获取团购活动失败，请稍后再试')
      } finally {
        loading.value = false
      }
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchGroupBuys()
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchGroupBuys()
    }

    const getStatusText = (status) => {
      switch (status) {
        case 0: return '未开始'
        case 1: return '进行中'
        case 2: return '已结束'
        case 3: return '已取消'
        default: return '未知状态'
      }
    }

    const getStatusClass = (status) => {
      switch (status) {
        case 0: return 'bg-blue-100 text-blue-800'
        case 1: return 'bg-green-100 text-green-800'
        case 2: return 'bg-gray-100 text-gray-800'
        case 3: return 'bg-red-100 text-red-800'
        default: return 'bg-gray-100 text-gray-800'
      }
    }

    const getButtonText = (status) => {
      switch (status) {
        case 0: return '查看详情'
        case 1: return '立即参团'
        case 2: return '查看详情'
        case 3: return '已取消'
        default: return '查看详情'
      }
    }

    const formatTimeRemaining = (timeString) => {
      const targetTime = new Date(timeString)
      const now = new Date()
      const diff = targetTime - now
      
      if (diff <= 0) return '已结束'
      
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      
      if (days > 0) {
        return `${days}天${hours}小时`
      } else if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      } else if (minutes > 0) {
        return `${minutes}分钟${seconds}秒`
      } else {
        return `${seconds}秒`
      }
    }

    const goToDetail = (id) => {
      router.push(`/group-buy/${id}`)
    }

    const formatImageUrl = (url) => {
      if (!url) return '/placeholder.png'
      if (url.startsWith('http')) return url
      // 如果是相对路径，添加基础URL
      return `${import.meta.env.VITE_API_BASE_URL || ''}${url}`
    }

    const handleImageError = (e) => {
      e.target.src = '/placeholder.png'
    }

    // 添加定时器以更新倒计时
    let timer = null
    
    onMounted(() => {
      fetchGroupBuys()
      // 每秒更新一次倒计时
      timer = setInterval(() => {
        // 强制组件重新渲染以更新倒计时
        groupBuys.value = [...groupBuys.value]
      }, 1000)
    })
    
    // 组件卸载时清除定时器
    onUnmounted(() => {
      if (timer) {
        clearInterval(timer)
        timer = null
      }
    })

    watch(activeTab, () => {
      currentPage.value = 1
      fetchGroupBuys()
    })

    return {
      groupBuys,
      loading,
      activeTab,
      tabs,
      currentPage,
      pageSize,
      total,
      handleCurrentChange,
      handleSizeChange,
      getStatusText,
      getStatusClass,
      getButtonText,
      formatTimeRemaining,
      goToDetail,
      formatImageUrl,
      handleImageError
    }
  }
}
</script> 